import json

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from baobaoxiong.upload_down import upload_img, download
from schoolmaster.models import *

# 调用月龄模块
from baobaoxiong.yueling import fn
from baobaoxiong.lat_long_query import *
# Create your views here.


@csrf_exempt
def start_location_views(request):
    yid = request.POST.get('yid')  # 扫二维码传的园所id
    uname = request.POST.get('uname')
    birth = request.POST.get('birth')
    gender = request.POST.get('gender')
    latitude = request.POST.get('latitude')  # 纬度
    longitude = request.POST.get('longitude')  # 经度

    if yid:
        # 获取园所
        school = School.objects.get(id=int(yid))
    else:
        id = get_area(float(latitude), float(longitude), 500)  # 获取园所id(经度，纬度，半径500米范围内)
        # 找不到园所返回error
        if id == 'failed':
            return JsonResponse({'status': 'failed', 'text': '附近没有园所'})
        school = School.objects.get(id=id)

    # 计算年龄，月份，总月龄
    yue_ling = fn(birth)
    # (23, 11, 287) 23年龄，11月份，287总月龄
    student = Student.objects.filter(uname=uname, birth=birth).order_by('-id').first()

    if student:
        # 学生存在时更新园所
        student.school_id = school.id
    else:
        # 不存在时保存数据
        student = Student()
        student.uname = uname
        student.gender = gender
        student.birth = birth
        student.school_id = school.id
        student.save()
    student1 = Student.objects.filter(uname=uname, birth=birth).order_by('-id').first()
    upload_img(str(school.logo))  # 上传图片到七牛云
    url = download(str(school.logo))
    dic = {
        'sid': student1.id,
        'name': uname,
        'age': "%s岁%s个月" % (str(yue_ling[0]), str(yue_ling[1])),
        'gender': gender,
        'schoollogo': url,
        'introduce': school.introduce
    }
    return JsonResponse(dic)


@csrf_exempt
def exam_views(request):
    uname = request.POST.get('uname')
    birth = request.POST.get('birth')
    gender = request.POST.get('gender')
    school = School.objects.get(id=1)
    student = Student.objects.filter(uname=uname, birth=birth).order_by('-id').first()

    if student:
        # 学生存在时更新园所
        student.school_id = school.id
    else:
        # 不存在时保存数据
        student = Student()
        student.uname = uname
        student.gender = gender
        student.birth = birth
        student.school_id = school.id
        student.save()
    student1 = Student.objects.filter(uname=uname, birth=birth).order_by('-id').first()
    # 获取学生姓名，查询学生表获取月龄，园所
    # 通过园所查找能力线，通过能力线查找对应的题，通过题查找选项，
    # 月龄用来获取适宜当前月龄的能力线
    #sid = request.POST.get('sid')  # 换成学生id
    #student = Student.objects.get(id=sid)
    #birth = student.birth
    yue_ling = fn(birth)
    age = yue_ling[2]
    if not Moonage.objects.filter(age=age).exists():
        return JsonResponse({'status': 'failed', 'text': '没有该年龄的题'})
    # school = student.school
    # 园所对应能力线
    powers = school.school_powers.all()

    # 获取与月龄对应能力线的对象
    l_powers = []
    for power in powers:
        # 获取月龄对应的能力线
        moonage = power.moonage_set.filter(age=age).first()
        if moonage:
            # l_powers.append(power)
            l_powers.append(moonage)

    # 获取测评题目
    l_tests = []
    for capacity in l_powers:
        tests = capacity.tests.filter(isDelete=False).all()
        if tests:
            for k in tests:
                l_tests.append(k)
    # 添加题和选项
    l_choices = []
    for chose in l_tests:
        choices = chose.question_choices.all()  # 获取测评题选项
        lst_option = []  # 添加每题的所有选项
        for question in choices:
            dic = {
                'id': question.id,  # 选项id
                'optionname': question.choiceName,  # 选项名
            }
            lst_option.append(dic)
        dic1 = {
            'title': chose.biaoti,  # 题名
            'option': lst_option,  # 该题选项
        }
        l_choices.append(dic1)  # 加进列表中
    dic2 = {
        'sid': student1.id,  # 学生id
        'count': len(l_choices),  # 题的数量
        'data': l_choices,  # 标题，选项数据
    }
    return JsonResponse(dic2)

@csrf_exempt
def exam_result_views(request):
    # 获取学生姓名
    sid = request.POST.get('sid')
    # 获取前端的选项 id
    ids = request.POST.get('ids')
    lst = json.loads(ids)

    student = Student.objects.get(id=sid)
    birth = student.birth
    yue_ling = fn(birth)
    age = yue_ling[2]
    # 保存数据到Testresult
    testresutl = Testresutl()
    testresutl.yueling = age
    testresutl.xuesheng = student
    testresutl.save()

    school = student.school
    # 园所对应能力线
    powers = school.school_powers.all()

    # 获取与月龄对应能力线的对象
    l_powers = []
    for power in powers:
        # 获取月龄对应的能力线
        moonage = power.moonage_set.filter(age=age).first()
        if moonage:
            # l_powers.append(power)
            l_powers.append(moonage)

    # 获取总分
    score = 0
    # 获取筛选出Test的数量
    i = 0
    # 获取测评结果Testresult对象
    obj = Testresutl.objects.filter(xuesheng_id=student.id, yueling=age).order_by('-id').first()
    for capacity in l_powers:
        # 保存数据到Testdetail中
        testdetail = Testdetail()

        able = capacity.abilities  # 月龄反向查找能力线
        testdetail.powername = able.powerTitle
        testdetail.testresult = obj
        testdetail.save()
        # tests = capacity.tests.all()   # 获取能力线题
        tests = capacity.tests.filter(isDelete=False).all()
        if not tests:
            return JsonResponse({'status': 'failed'})
        grade = 0  # 计算能力线结果
        for k in tests:
            i = i + 1
            choices = k.question_choices.all()  # 获取每道题选项
            for ch in choices:
                leap = 0
                # 获取每道题选项得分
                for id in lst:
                    if ch.id == int(id):
                        score = score + ch.grade
                        grade = grade + ch.grade

                        # 保存数据到 Questionresult表中
                        questionresult = Questionresult()
                        # 获取测评详情Testdetail对象
                        chr = Testdetail.objects.filter(testresult_id=obj.id, powername=capacity.abilities.powerTitle).first()
                        questionresult.questionName = k.biaoti
                        questionresult.getscore = ch.grade
                        questionresult.testdetail = chr
                        questionresult.save()
                        leap = 1
                        break
                if leap:
                    break
        grade = grade / len(tests)
        result = ''
        if grade > 0 and grade < 1.5:
            result = '劣'
        elif (grade > 1.5 or grade == 1.5) and grade < 2.5:
            result = '差'
        elif (grade > 2.5 or grade == 2.5) and grade < 3.5:
            result = '中'
        elif (grade > 3.5 or grade == 3.5) and grade < 4.5:
            result = '良'
        elif (grade > 4.5 or grade == 4.5) and(grade < 5 or grade == 5):
            result = '优'
        # 保存结果 到Testdetail中
        obj2 = Testdetail.objects.filter(powername=capacity.abilities.powerTitle, testresult_id=obj.id).first()
        obj2.result = result
        obj2.save()
    # 计算总分
    score = int((score / (i*5)) * 100)
    # 保存到 Testresult 中
    obj.score = score
    obj.save()

    lst_powers = []
    # 筛选对应能力线结果
    testpowers = Testdetail.objects.filter(testresult_id=obj.id)
    for power_result in testpowers:
        dic = {
            'powername': power_result.powername,  # 能力线名
            'result': power_result.result,  # 结果
        }
        lst_powers.append(dic)

    upload_img(str(student.photo))  # 上传图片到七牛云
    url = download(str(student.photo))
    dic1 = {
        'name': student.uname,
        'photo': url,
        'age': age,
        'gender': student.gender,
        'score': obj.score,
        'data': lst_powers  # 能力线，结果
    }
    return JsonResponse(dic1)





